package com.cch.android.util.contacts;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.telephony.TelephonyManager;

import com.cch.android.util.Constant;
import com.cch.android.util.MyLog;
/**
 * 获取联系人列表
 * @author Administrator
 *
 */

public class Contacts {

	private Context mContext;
	  private TelephonyManager mTelephonyManager;  
	    private String mString = "";  
	public Contacts(Context mContext){
		this.mContext=mContext;
	}

	/**
	 * 获取联系人列表
	 * @return
	 */
	public  List<Person> getPerson() {
		
		Uri uri=ContactsContract.Data.CONTENT_URI;
		ArrayList<String> simIdList = new ArrayList<String>();
        String i="0";
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor=resolver.query(uri,null,null, null, null);
        ArrayList<String> nameSimList=null;
        Cursor mcursor = resolver.query(
        		   RawContacts.CONTENT_URI,
        		   new String[]{RawContacts._ID,RawContacts.ACCOUNT_TYPE,RawContacts.CONTACT_ID},
        		   RawContacts.ACCOUNT_TYPE + " <> 'com.anddroid.contacts.sim' "
        		    + " AND " + RawContacts.ACCOUNT_TYPE + " <> 'com.google' " //if you //don't want to google contacts also
        		   ,
        		   null,
        		   null);
        while (mcursor.moveToNext()) {
        	
        	MyLog.log("测试："+mcursor.getString(2));
        	simIdList.add(mcursor.getString(2));
        	
        }
        cursor.moveToFirst();
        List<Person> allList=new ArrayList<Person>();
        List<Person> list=new ArrayList<Person>();
        Person person = null;
        List<String> phone = null;
        while(cursor.getCount()>cursor.getPosition()){
        	String id=cursor.getString(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
//        	String contact_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
        	String info=cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
            String mimeType=cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
           
            
            if(!id.equals(i)){
            	if(person!=null||!i.equals("0")){
        			person.setPhone(phone);
        			if(person.getName()!=null&&!"".equals(person.getName())&&id!=null){
        				
        				
//        				allList.add(person);  				
        				if(simIdList!=null && simIdList.size()>0)
        				for (String simId : simIdList) {
        					if(id.equals(simId)){
        						MyLog.log("联系人id:"+Long.parseLong(id)+",联系人姓名："+person.getName());
        						list.add(person);
        					}
						}
        			}
        		}
        		person=new Person();
        		phone=new ArrayList<String>();
        		i=id;
            }
            if(id.equals(i)){
            	if(mimeType.equals("vnd.android.cursor.item/email_v2")){
            		if(person.getEmail()==null||person.getEmail().equals("")){
            			person.setEmail(info);
            		}else{
            			person.setEmail("");
            		}
            	}else if(mimeType.equals("vnd.android.cursor.item/postal-address_v2")){
            		if(person.getAddress()==null||person.getAddress().equals("")){
            			person.setAddress(info);
            		}else{
            			person.setAddress("");
            		}
            	}else if(mimeType.equals("vnd.android.cursor.item/phone_v2")){
            		if(person.getPhone()==null||person.getPhone().equals("")){
            			phone.add(info);
            		}else{
            			phone.add("");
            		}
            	}else if(mimeType.equals("vnd.android.cursor.item/name")){
            		if(person.getName()==null||person.getName().equals("")){
            			person.setId(Long.parseLong(id));
            			person.setName(info);
            		}else{
            			person.setName("");
            		}
            	}
            }	
            cursor.moveToNext();
            if(cursor.getCount()==cursor.getPosition()){
//    			list.add(person);
            	if(person!=null){
            		person.setPhone(phone);
            		if(person.getName()!=null&&!"".equals(person.getName())&&id!=null){
        				MyLog.log("联系人id:"+Long.parseLong(id)+",联系人姓名："+person.getName());
//        				person.setId(Long.parseLong(id));
//            			person.setName(person.getName());
        				list.add(person);
        			}
            	}
              }
            }
//        allList.removeAll(list);
		return list;
	}
	private final static boolean OldSDK = (Constant.getAndroidSDKVersion()< 5 )? true : false;
	 /**
	  * 取得联系人头像
	  * @param context
	  * @param pid
	  * @param defaultIco
	  * @return
	  */
    public static Bitmap getContactPhoto(Context context, long pid,int defaultIco){
        if (OldSDK){
            Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, pid);
            return  People.loadContactPhoto(context, uri,defaultIco, null);
        }
        else
           return getContactPhoto5(context, pid, defaultIco);
    }
 
    private static Bitmap getContactPhoto5(Context c, long personId,int defaultIco){
        byte[] data = new byte[0];
        Uri u = Uri.parse("content://com.android.contacts/data");// AND (is_super_primary =1 or is_primary=1)
        String where ="raw_contact_id = " + personId + " AND mimetype ='vnd.android.cursor.item/photo'";
        Cursor cursor = c.getContentResolver().query(u, null, where,    null, null);
        if (cursor.moveToFirst()) {
          data = cursor.getBlob(cursor.getColumnIndex("data15"));
        }
        cursor.close();
        if (data ==null ||data.length == 0){
            return BitmapFactory.decodeResource(c.getResources(), defaultIco);
        }
        else
            return BitmapFactory.decodeByteArray(data, 0, data.length);
    }
    /**
     * 设置联系人头像
     * @param context
     * @param b
     * @param persionID
     * @param Sync
     */
    public boolean setPersonPhotoBytes(Context context,byte[] b, long persionID, boolean Sync) {
            if (OldSDK){
              Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, persionID);
              People.setPhotoData(context.getContentResolver(), myPerson, b);
              if (! Sync){
                ContentValues values = new ContentValues();
                values.put("_sync_dirty", 0);
                context.getContentResolver().update(myPerson, values, null, null);
              }
              return true;
            }
            else
                return setContactPhoto5(context.getContentResolver(), b, persionID, Sync);
        }
     
     private boolean setContactPhoto5(ContentResolver c, byte[] bytes,long personId, boolean Sync) {
    	    MyLog.log("设置联系人头像:"+personId);
    	    try {
    	    	 ContentValues values = new ContentValues();
    	            Uri u = Uri.parse("content://com.android.contacts/data");
    	            int photoRow = -1;
    	            String where ="raw_contact_id = " + personId + " AND mimetype ='vnd.android.cursor.item/photo'";
    	            Cursor cursor = c.query(u, null, where, null, null);
    	            int idIdx = cursor.getColumnIndexOrThrow("_id");
    	            if (cursor.moveToFirst()) {
    	                photoRow = cursor.getInt(idIdx);
    	            }
    	            cursor.close();
    	            values.put("raw_contact_id", personId);
    	            values.put("is_super_primary", 1);
    	            values.put("data15", bytes);
    	            values.put("mimetype","vnd.android.cursor.item/photo");
    	            if (photoRow >= 0) {
    	                c.update(u, values, " _id= " + photoRow, null);
    	            } else {
    	                c.insert(u, values);
    	            }
    	            if (! Sync){
    	                u = Uri.withAppendedPath(Uri.parse("content://com.android.contacts/raw_contacts"), String.valueOf(personId));
    	                values = new ContentValues();
    	                values.put("dirty", 0);
    	                c.update(u, values, null, null);
    	            }
    	            return true;
			} catch (Exception e) {
				return false;
			}
        }
     private int getSimState(){  
         return mTelephonyManager.getSimState();  
     }  
        
     private void isSimExist(){  
         mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);  
          int simState = mTelephonyManager.getSimState();  
    
          switch (simState) {  
    
              case TelephonyManager.SIM_STATE_ABSENT:  
                  mString = "无卡";  
                  // do something  
                  break;  
    
              case TelephonyManager.SIM_STATE_NETWORK_LOCKED:  
                  mString = "需要NetworkPIN解锁";  
                  // do something  
    
                  break;  
    
              case TelephonyManager.SIM_STATE_PIN_REQUIRED:  
                  mString = "需要PIN解锁";  
                  // do something  
                  break;  
    
              case TelephonyManager.SIM_STATE_PUK_REQUIRED:  
                  mString = "需要PUN解锁";  
                  // do something  
                  break;  
    
              case TelephonyManager.SIM_STATE_READY:  
                  mString = "良好";  
                  // do something  
                  break;  
    
              case TelephonyManager.SIM_STATE_UNKNOWN:  
                  mString = "未知状态";  
                  // do something  
                  break;  
          }  
     }  
}
